﻿using System.Linq;
using NetSurveillance.WebApp.DataServices.Models;
using ServiceStack.OrmLite;

namespace NetSurveillance.WebApp.DataServices.Implementations
{
    public class UserService : BaseService<User>
    {
        public UserService(string connStr)
            : base(connStr)
         {
         }

        public ServiceResult ValidateAccount(string userName, string passWord, out User user)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                user = db.Select<User>(p => p.UserName == userName && p.Password == passWord && p.StatusToken != 0).FirstOrDefault();
                if (user == null)
                    return new ServiceResult {ExecutedSuccess = true, Message = "User Name Or Password is incorrect."};
            }
            return ServiceResult.SuccessResult;
        }

        public ServiceResult SaveAcctPermission(long userId, PermissionType pms)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                var userPms = db.SingleOrDefault<UserPermission>(" \"UserId\"={0}", userId) ??
                              new UserPermission {UserId = userId};
                userPms.Permission = pms;
                db.Save(userPms);
                return ServiceResult.SuccessResult;
            }
        }

        public UserPermission GetAcctPermission(long userId)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                return db.SingleOrDefault<UserPermission>(" \"UserId\"={0}", userId);
            }
        }
    }
}